package com.chenjt.netty.two_socket.chat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/8/8 17:13
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 所有与服务器端建立连接的客户端的channel对象
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.forEach(ch->{
            //筛选出客户端本身发消息的连接（除了自己其他客户端都收到消息）
            if(channel != ch){
                ch.writeAndFlush(channel.remoteAddress()+" 发送的消息："+msg + "\n");
            }else{
                ch.writeAndFlush(" [自己] " + msg + "\n");
            }
        });

    }

    /**
     * 客户端与服务端建立连接时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        //有连接进来之后给所有在channelGroup中的连接发送消息
        channelGroup.writeAndFlush("[服务器] - "+ channel.remoteAddress()+" 加入\n");

        channelGroup.add(channel);

    }


    /**
     * 有客户端断开连接时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.writeAndFlush("[服务器] - "+ channel.remoteAddress()+" 离开\n");

        //netty会自动调用以下代码，可以不加上去
//        channelGroup.remove(channel);
        System.out.println(channelGroup.size());

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+" 上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+" 下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
